package com.zeldu.chat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zeldu.chat.pojo.RequestMessage;
import com.zeldu.chat.pojo.ResponseMessage;
import com.zeldu.chat.service.ChatService;
import com.zeldu.chat.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ChatServiceImpl implements ChatService {

    private static Map<String, Map<String, Session>> allClients = new ConcurrentHashMap<>();

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String[] open(Session session, String jsondata) {
        JSONObject jsonObject = JSON.parseObject(jsondata);
        String courseId = jsonObject.getString("courseId");
        String userId = jsonObject.getString("userId");
        String userName = jsonObject.getString("name");
        //存储客户端链接
        Map<String, Session> courseClients = new ConcurrentHashMap<>();
        courseClients.put(userId, session);
        allClients.put(courseId, courseClients);
        redisUtil.hset(courseId,userId,userName);
        System.out.println(courseId+":"+userId+":加入连接");
        return new String[]{courseId,userId};
    }

    @Override
    public void close(String courseId, String userId) {
        redisUtil.hdel(courseId,userId);
        allClients.get(courseId).remove(userId);
        System.out.println(courseId+":"+userId+":断开连接");
    }

    @Override
    public void onMessage(String message) {
        //接收数据解析
        JSONObject jsonObject=JSON.parseObject(message);
        RequestMessage requestMessage = new RequestMessage();
        requestMessage.setCourseId(jsonObject.getString("courseId"));
        requestMessage.setUserId(jsonObject.getString("userId"));
        requestMessage.setMessage(jsonObject.getString("message"));
        //处理返回数据
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setMessage(requestMessage.getMessage());
        String name= (String) redisUtil.hget(requestMessage.getCourseId(), requestMessage.getUserId());
        responseMessage.setName(name);
        String str=JSON.toJSONString(responseMessage);
        //发送消息
        Map<String, Session> courseClients=allClients.get(requestMessage.getCourseId());
        for(Session session:courseClients.values()){
            synchronized (session){
                new Thread(() -> session.getAsyncRemote().sendText(str)).start();
            }

        }


    }
}
